<template>
  <el-dialog :model-value="dialogVisible" :title="state.title" width="40%" align-center @closed="handleCancel">
    <el-form ref="refForm" :model="form.data" :rules="form.rules" label-width="80px" label-position="right">
      <el-form-item prop="formName" label="表单名称">
        <el-input v-model="form.data.formName" placeholder="请输入表单名称"></el-input>
      </el-form-item>
      <el-form-item prop="formCode" label="表单编号">
        <el-input v-model="form.data.formCode" placeholder="请输入表单编号"></el-input>
      </el-form-item>
      <el-form-item prop="processDefKey" label="流程">
        <el-select v-model="form.data.processDefKey" style="width: 100%" placeholder="请选择流程">
          <el-option v-for="f in form.flowKeys" :key="f.value" :value="f.value" :label="f.label" />
        </el-select>
      </el-form-item>
      <el-form-item ref="refFlowDef" prop="processDefId" class="formDef-item">
        <div class="formDef-wrap">
          <el-radio-group v-model="form.useVersion" class="radio-group" @change="onChangeUseVersion">
            <el-radio :label="1">使用最新版本</el-radio>
            <el-radio :label="2">使用特定版本</el-radio>
          </el-radio-group>
          <div class="version">
            <el-select
              v-model="form.data.processDefId"
              v-show="form.useVersion == 2"
              size="small"
              style="width: 100%"
              placeholder="请输入选择流程版本"
              @change="onChangeVersion"
            >
              <el-option
                v-for="v in flowVersions"
                :key="v.deploymentId"
                :value="v.deploymentId"
                :label="`V${v.version}`"
              />
            </el-select>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item prop="icon" label="图标">
        <el-input v-model="form.data.icon" placeholder="请输入图标"></el-input>
      </el-form-item> -->
      <!-- <el-form-item prop="status" label="状态（正常1/草稿0）">
        <el-input v-model="form.data.status" placeholder="请输入状态（正常1/草稿0）"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { withDefaults, computed, reactive, ref, nextTick, onMounted } from 'vue'
import {
  ElDialog,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio
} from 'element-plus'
import { util } from '@/utils'
import { formDefApi } from '@/api/modules/flow/formDef'
import type { FormDef } from '@/api/modules/flow/formDef'
import { flowDefApi } from '@/api/modules/flow/flowDef'

const props = withDefaults(defineProps<{ visible: boolean }>(), {
  visible: false
})
const emits = defineEmits(['success', 'update:visible'])

const dialogVisible = computed(() => props.visible)

const refForm = ref()
const refFlowDef = ref()

const checkProcessDefId = (rule: any, value: any, callback: any) => {
  if (value === '' && form.useVersion == 2) {
    callback(new Error('请选择特定流程版本号'))
  } else {
    callback()
  }
}
const form = reactive<{
  data: FormDef
  useVersion: number
  rules: any
  flowData: any
  flowKeys: any[]
}>({
  data: {} as FormDef,
  useVersion: 1,
  rules: {
    formName: [{ required: true, message: '请输入表单名称' }],
    formCode: [{ required: true, message: '请输入表单编号' }],
    processDefId: [{ validator: checkProcessDefId, trigger: 'blur' }]
  },

  flowData: {},
  flowKeys: []
})

const state = computed(() => {
  if (form.data.formId) {
    return { isCreate: false, title: '修改表单' }
  } else {
    return { isCreate: true, title: '新建表单' }
  }
})

const getFlow = () => {
  flowDefApi.findDefList().then(resp => {
    if (resp.success) {
      form.flowData = resp.data
      for (const key in resp.data) {
        form.flowKeys.push({ value: key, label: resp.data[key][0]['name'] })
      }
    }
  })
}
onMounted(getFlow)

const flowVersions = computed(() => {
  return form.flowData[form.data.processDefKey]
})

const onChangeUseVersion = () => {
  refFlowDef.value.clearValidate()
}
const onChangeVersion = () => {
  refForm.value.validateField('processDefId')
}

const handleSave = () => {
  refForm.value.validate((valid: boolean) => {
    if (valid) {
      if (form.useVersion == 1) {
        form.data.processDefId = ''
      }
      saveCallback(formDefApi.save(form.data))
    }
  })
}
const saveCallback = (promise: Promise<AxiosType.Response>) => {
  promise.then(resp => {
    if (resp.success) {
      ElMessage.success(`已${state.value.title} [ ${form.data.formName} ]`)
      emits('success')
      handleCancel()
    } else {
      ElMessage.error(resp.message)
    }
  })
}

const handleCancel = () => {
  form.data = {} as FormDef
  refForm.value.resetFields()
  emits('update:visible', false)
}

const setFormData = (data: FormDef) => {
  nextTick(() => {
    form.data = util.cloneObject(data)
    form.useVersion = form.data.processDefId ? 2 : 1
  })
}
defineExpose({ setFormData })
</script>

<style lang="scss" scoped>
.formDef-item {
  .formDef-wrap {
    display: flex;
    align-items: center;
    width: 100%;
    .radio-group {
      width: 255px;
    }
    .version {
      flex-grow: 1;
    }
  }
  :deep(.el-form-item__error) {
    margin-left: 255px;
  }
}
</style>
